package pcsr.hwVirtualization;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

class DriverFactory {
	private static final String DRIVER_CLASS = "pcsrdriverclass";
	private static final String PROPSFNAME = "PCSR.properties";
	private static final String UDIR = System.getProperty("user.dir");
	private static final String UHOME = System.getProperty("user.home");
	private static final String FSEP = System.getProperty("file.separator");

	public static IDriverActions createInstance() 
	{
		
		/* Create properties with defaults for appropriate OS */
		Properties props = getDefaults();

		/* Load settings from PCSR.properties file */
		File file = new File(UDIR + FSEP + PROPSFNAME);
		if(!file.exists())
			file = new File(UHOME + FSEP + PROPSFNAME);
		System.out.println("Properties location: " + file.getAbsolutePath());
		try {
			if(file.exists()) 
				props.load(new FileInputStream(file));
			else {
				System.out.println(PROPSFNAME + " does NOT exist. Creating.");

				file.createNewFile();
				// NOTE: Default settings might not be stored?
				props.store(new FileOutputStream(file), "Auto-generated PCSR Properties file");
			}

		} catch(IOException e) {
			System.out.println(e);
		}

		String driverclassname = props.getProperty(DriverFactory.DRIVER_CLASS);
		if (driverclassname != null) 
		{	
			IDriverActions ret = null;
			try {
				ret = (IDriverActions) ( Class.forName( driverclassname ).newInstance() );
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return ret;
			
		}

		return null;
	}

	/**
	 * This creates a Properties object with some default settings.
	 * The Properties class will resort to using default settings
	 * if a setting is blank.
	 * @return Properties object with some default settings
	 */
	private static Properties getDefaults() {
		Properties defaults = new Properties();
		
		defaults.setProperty(DriverFactory.DRIVER_CLASS, "EPuck");
		
		return defaults;
	}
}
